{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\">Segmentation Evaluation</h1>\n",
    "\n",
    "Evaluating segmentation algorithms is most often done using reference data to which you compare your results. \n",
    "\n",
    "In the medical domain reference data is commonly obtained via manual segmentation by an expert (don't forget to thank your clinical colleagues for their hard work). When you are resource limited, the reference data may be defined by a single expert. This is less than ideal. When multiple experts provide you with their input then you can potentially combine them to obtain reference data that is closer to the ever elusive \"ground truth\". In this notebook we show two approaches to combining input from multiple observers, majority vote and the Simultaneous Truth and Performance Level\n",
    "Estimation [(STAPLE)](http://crl.med.harvard.edu/research/staple/).\n",
    "\n",
    "Once we have a reference, we compare the algorithm's performance using multiple criteria, as usually there is no single evaluation measure that conveys all of the relevant information. In this notebook we illustrate the use of the following evaluation criteria:\n",
    "* Overlap measures:\n",
    "  * Jaccard and Dice coefficients \n",
    "  * false negative and false positive errors\n",
    "* Surface distance measures:\n",
    "  * mean, median, max and standard deviation between surfaces\n",
    "* Volume measures:\n",
    "  * volume similarity $ \\frac{2*(v1-v2)}{v1+v2}$\n",
    "\n",
    "The relevant criteria are task dependent, so you need to ask yourself whether you are interested in detecting spurious errors or not (mean or max surface distance), whether over/under segmentation should be differentiated (volume similarity and Dice or just Dice), and what is the ratio between acceptable errors and the size of the segmented object (Dice coefficient may be too sensitive to small errors when the segmented object is small and not sensitive enough to large errors when the segmented object is large).\n",
    "\n",
    "The data we use in the notebook is a set of manually segmented liver tumors from a single clinical CT scan. A larger dataset (four scans) is freely available from this [MIDAS repository](http://www.insight-journal.org/midas/collection/view/38). The relevant publication is: T. Popa et al., \"Tumor Volume Measurement and Volume Measurement Comparison Plug-ins for VolView Using ITK\", SPIE Medical Imaging: Visualization, Image-Guided Procedures, and Display, 2006.\n",
    "\n",
    "<b>Note</b>: The approach described here can also be used to evaluate Registration, as illustrated in the [free form deformation notebook](65_Registration_FFD.ipynb)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "library(SimpleITK)\n",
    "\n",
    "source(\"downloaddata.R\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Utility functions\n",
    "\n",
    "Display related utility functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "## save the default options in case you need to reset them\n",
    "if (!exists(\"default.options\")) \n",
    "{\n",
    "default.options <- options()\n",
    "}\n",
    "# display 2D images inside the notebook (colour and greyscale)\n",
    "show_inline <- function(object, Dwidth=grid::unit(5, \"cm\"))\n",
    "{\n",
    "  ncomp <- object$GetNumberOfComponents()\n",
    "  if (ncomp == 3) {\n",
    "      ## colour\n",
    "      a <- as.array(object)\n",
    "      a <- aperm(a, c(2, 1, 3))\n",
    "  } else if (ncomp == 1) {\n",
    "      a <- t(as.array(object))\n",
    "  } else {\n",
    "      stop(\"Only deals with 1 or 3 component images\")\n",
    "  }\n",
    "  rg <- range(a)\n",
    "  A <- (a - rg[1]) / (rg[2] - rg[1])\n",
    "  dd <- dim(a)\n",
    "  sp <- object$GetSpacing()\n",
    "  sz <- object$GetSize()\n",
    "  worlddim <- sp * sz\n",
    "  worlddim <- worlddim / worlddim[1]\n",
    "  W <- Dwidth\n",
    "  H <- Dwidth * worlddim[2]\n",
    "  WW <- grid::convertX(W*1.1, \"inches\", valueOnly=TRUE)\n",
    "  HH <- grid::convertY(H*1.1, \"inches\", valueOnly=TRUE)\n",
    "  ## here we set the display size\n",
    "  ## Jupyter only honours the last setting for a cell, so\n",
    "  ## we can't reset the original options. That needs to\n",
    "  ## be done manually, using the \"default.options\" stored above\n",
    "  ## Obvious point to do this is before plotting graphs\n",
    "  options(repr.plot.width = WW, repr.plot.height = HH)\n",
    "  grid::grid.raster(A, default.units=\"mm\", width=W, height=H)\n",
    "}\n",
    "\n",
    "# Tile images to create a single wider image.\n",
    "color_tile <- function(images)\n",
    "{\n",
    "  width <- images[[1]]$GetWidth()\n",
    "  height <- images[[1]]$GetHeight()\n",
    "  tiled_image <- Image(c(length(images) * width, height), images[[1]]$GetPixelID(), images[[1]]$GetNumberOfComponentsPerPixel())\n",
    "  \n",
    "  for(i in 1:length(images))\n",
    "  {        \n",
    "    tiled_image <- Paste(tiled_image, images[[i]], images[[i]]$GetSize(), c(0, 0), c((i - 1) * width, 0))\n",
    "  }\n",
    "  return( tiled_image )\n",
    "}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fetch the data\n",
    "\n",
    "Retrieve a single CT scan and three manual delineations of a liver tumor. Visual inspection of the data highlights the variability between experts. \n",
    "\n",
    "All computations are done in 3D (the dimensionality of the images). For display purposes we selected a single slice_for_display. Change this variable's value to see other slices.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "slice_for_display <- 77\n",
    "\n",
    "image <- ReadImage(fetch_data(\"liverTumorSegmentations/Patient01Homo.mha\"))\n",
    "# For display we need to window-level the slice (map the high dynamic range to a reasonable display) \n",
    "display_slice <- Cast(IntensityWindowing(image[,,slice_for_display], \n",
    "                                         windowMinimum=-1024, \n",
    "                                         windowMaximum=976), \n",
    "                      \"sitkUInt8\") \n",
    "\n",
    "segmentation_file_names <- list(\"liverTumorSegmentations/Patient01Homo_Rad01.mha\", \n",
    "                                \"liverTumorSegmentations/Patient01Homo_Rad02.mha\",\n",
    "                                \"liverTumorSegmentations/Patient01Homo_Rad03.mha\")                          \n",
    "segmentations <- lapply(segmentation_file_names, function(x) ReadImage(fetch_data(x),\"sitkUInt8\"))\n",
    "\n",
    "# Overlay the segmentation contour from each of the segmentations onto the \"slice_for_display\"\n",
    "display_overlays <- lapply(segmentations, \n",
    "                           function(seg) LabelMapContourOverlay(Cast(seg[,,slice_for_display], \"sitkLabelUInt8\"), \n",
    "                                                                display_slice,\n",
    "                                                                opacity = 1))\n",
    "   \n",
    "show_inline(color_tile(display_overlays),grid::unit(15, \"cm\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Derive a reference\n",
    "\n",
    "There are a variety of ways to derive a reference segmentation from multiple expert inputs. Several options, there are more, are described in \"A comparison of ground truth estimation methods\", A. M. Biancardi, A. C. Jirapatnakul, A. P. Reeves. \n",
    "\n",
    "Two methods that are available in SimpleITK are <b>majority vote</b> and the <b>STAPLE</b> algorithm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Use majority voting to obtain the reference segmentation. Note that this filter does not resolve ties. In case of \n",
    "# ties, it will assign max_label_value+1 or a user specified label value (labelForUndecidedPixels) to the result. \n",
    "# Before using the results of this filter you will have to check whether there were ties and modify the results to\n",
    "# resolve the ties in a manner that makes sense for your task. The filter implicitly accommodates multiple labels.\n",
    "labelForUndecidedPixels <- 10\n",
    "reference_segmentation_majority_vote <- LabelVoting(segmentations, labelForUndecidedPixels)    \n",
    "\n",
    "show_inline(LabelMapContourOverlay(Cast(reference_segmentation_majority_vote[,,slice_for_display], \"sitkLabelUInt8\"), display_slice, opacity = 1),\n",
    "            grid::unit(5, \"cm\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Use the STAPLE algorithm to obtain the reference segmentation. This implementation of the original algorithm\n",
    "# combines a single label from multiple segmentations, the label is user specified. The result of the\n",
    "# filter is the voxel's probability of belonging to the foreground. We then have to threshold the result to obtain\n",
    "# a reference binary segmentation.\n",
    "foregroundValue <- 1\n",
    "threshold <- 0.95\n",
    "reference_segmentation_STAPLE_probabilities <- STAPLE(segmentations, foregroundValue) \n",
    "# We use the overloaded operator to perform thresholding, another option is to use the BinaryThreshold function.\n",
    "reference_segmentation_STAPLE <- reference_segmentation_STAPLE_probabilities > threshold\n",
    "\n",
    "show_inline(LabelMapContourOverlay(Cast(reference_segmentation_STAPLE[,,slice_for_display], \"sitkLabelUInt8\"), display_slice, opacity = 1),\n",
    "            grid::unit(5, \"cm\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Evaluate segmentations using the reference\n",
    "\n",
    "Once we derive a reference from our experts input we can compare segmentation results to it.\n",
    "\n",
    "Note that in this notebook we compare the expert segmentations to the reference derived from them. This is not relevant for algorithm evaluation, but it can potentially be used to rank your experts.\n",
    "\n",
    "### Utility functions\n",
    "These functions compute standard overlap and surface distance measures used when comparing segmentations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Compare the two given segmentations using overlap measures (Jaccard, Dice, etc.)\n",
    "compute_overlap_measures <- function(segmentation, reference_segmentation)\n",
    "{\n",
    "  omf <- LabelOverlapMeasuresImageFilter()\n",
    "  omf$Execute(reference_segmentation, segmentation)\n",
    "  result <- c(omf$GetJaccardCoefficient(), omf$GetDiceCoefficient(), \n",
    "              omf$GetVolumeSimilarity(), omf$GetFalseNegativeError(), omf$GetFalsePositiveError())\n",
    "  names(result) <- c(\"JaccardCoefficient\", \"DiceCoefficient\", \"VolumeSimilarity\",\n",
    "                     \"FalseNegativeError\", \"FalsePositiveError\")\n",
    "  return (result)\n",
    "}\n",
    "\n",
    "# Compare a segmentation to the reference segmentation using distances between the two surfaces. To facilitate\n",
    "# surface distance computations we use a distance map of the reference segmentation. \n",
    "compute_surface_distance_measures <- function(segmentation, reference_distance_map)\n",
    "{\n",
    "  segmented_label = 1\n",
    "\n",
    "  # Get the intensity statistics associated with each of the labels, combined\n",
    "  # with the distance map image this gives us the distances between surfaces.         \n",
    "  lisf <- LabelIntensityStatisticsImageFilter()\n",
    "\n",
    "  # Get the pixels on the border of the segmented object\n",
    "  segmented_surface <- LabelContour(segmentation)\n",
    "  lisf$Execute(segmented_surface, reference_distance_map)\n",
    "  result <- c(lisf$GetMean(segmented_label), lisf$GetMedian(segmented_label),\n",
    "              lisf$GetStandardDeviation(segmented_label), lisf$GetMaximum(segmented_label))\n",
    "  names(result) <- c(\"Mean\", \"Median\", \"SD\", \"Max\")\n",
    "  return (result)              \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Evaluate the three segmentations with respect to the STAPLE based reference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "overlap_measures <- t(sapply(segmentations, compute_overlap_measures, \n",
    "                           reference_segmentation=reference_segmentation_STAPLE))\n",
    "overlap_measures <- as.data.frame(overlap_measures)\n",
    "overlap_measures$rater <- rownames(overlap_measures)\n",
    "\n",
    "distance_map_filter <- SignedMaurerDistanceMapImageFilter()\n",
    "distance_map_filter$SquaredDistanceOff()\n",
    "STAPLE_reference_distance_map <-\n",
    "  abs(distance_map_filter$Execute(reference_segmentation_STAPLE))\n",
    "\n",
    "surface_distance_measures <- t(sapply(segmentations, \n",
    "                                      compute_surface_distance_measures, \n",
    "                                      reference_distance_map=STAPLE_reference_distance_map))\n",
    "surface_distance_measures <- as.data.frame(surface_distance_measures)\n",
    "surface_distance_measures$rater <- rownames(surface_distance_measures)\n",
    "\n",
    "# Look at the results using the notebook's default display format for data frames\n",
    "overlap_measures\n",
    "surface_distance_measures"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Improved output\n",
    "\n",
    "If the [tidyr](https://cran.r-project.org/web/packages/tidyr/index.html) and [ggplot2](https://cran.r-project.org/web/packages/ggplot2/index.html) packages are installed in your R environment then you can easily produce high quality output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "library(tidyr)\n",
    "library(ggplot2)\n",
    "## reset the plot size\n",
    "options(default.options)\n",
    "overlap.gathered <- gather(overlap_measures, key=Measure, value=Score, -rater)\n",
    "ggplot(overlap.gathered,\n",
    "       aes(x=rater, y=Score, group=Measure, fill=Measure)) +\n",
    "    geom_bar(stat=\"identity\", position=\"dodge\", colour='black', alpha=0.5)\n",
    "\n",
    "surface_distance.gathered <- gather(surface_distance_measures, key=Measure, value=Score, -rater)\n",
    "ggplot(surface_distance.gathered,\n",
    "       aes(x=rater, y=Score, group=Measure, fill=Measure)) +\n",
    "    geom_bar(stat=\"identity\", position=\"dodge\", colour='black', alpha=0.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also export the data as a table for your LaTeX manuscript using the [xtable](https://cran.r-project.org/web/packages/xtable/index.html) package, just copy paste the output of the following cell into your document. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "library(xtable)\n",
    "sd <- surface_distance_measures\n",
    "sd$rater <- NULL\n",
    "print(xtable(sd, caption=\"Segmentation surface distance measures per rater.\", \n",
    "       label=\"tab:surfdist\", digits=2))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "3.2.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
